<?php

namespace JsonLowCode\Factory;

use BadMethodCallException;
use JsonLowCode\Traits\Macroable;
use JsonLowCode\PageCache;
use JsonLowCode\Traits\HasPageCache;

/**
 * UIFactory 工厂类
 */
class UIFactory
{
    public static ?UIFactory $instance = null;

    protected PageCache $pageCache;

    protected ?string $cacheKey = null;

    use Macroable, HasPageCache;

    protected array $methods = [

    ];


    public function __construct(){
        $this->pageCache = PageCache::make();
//        $components = config('lowcode.components',[]);
//        $methods = array_merge($this->methods,$components);
//        foreach ($methods as $method=>$class){
//            self::macro($method,$class);
//        }
    }

    public static function make(): static
    {
        if (!self::$instance instanceof self) {
            self::$instance = new static();
        }
        return self::$instance;
    }



    /**
     * Dynamically handle calls to the class.
     *
     * @param  string  $method
     * @param  array  $parameters
     * @return mixed
     *
     * @throws BadMethodCallException
     */
    public function __call($method, $parameters)
    {
        $macro = '\\JsonLowCode\\UI\\' . ucfirst($method);
        if (!class_exists($macro)) {
            if (!static::hasMacro($method)) {
                throw new BadMethodCallException(sprintf(
                    'Method %s::%s does not exist.', static::class, $method
                ));
            }
            $macro = static::$macros[$method];
        }
        if ($macro instanceof \Closure) {
            return call_user_func_array($macro->bindTo($this, static::class),$parameters);
        }
        return new $macro(...$parameters);
    }
}
